package github.sf.fw.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import github.sf.fw.utils.Ids;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

//@Component
public class InsertOrUpdateMetaObjectHandler implements MetaObjectHandler {
    public final static String CREATED_BY = "createdBy";
    public final static String CREATED_TIME = "createdTime";
    public final static String ID = "id";
    public final static String UPDATED_BY = "updatedBy";
    public final static String UPDATED_TIME = "updatedTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter(CREATED_BY)) {
            setFieldValByName(CREATED_BY, "System", metaObject);
        }
        if (metaObject.hasGetter(CREATED_TIME)) {
            setFieldValByName(CREATED_TIME, new Date(), metaObject);
        }
        if (metaObject.hasGetter(ID)) {
            if (metaObject.getValue(ID) == null) {
                setFieldValByName(ID, Ids.getSnowflake().nextId(), metaObject);
            }
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter(UPDATED_BY)) {
            setFieldValByName(UPDATED_BY, "System", metaObject);
        }
        if (metaObject.hasGetter(UPDATED_TIME)) {
            setFieldValByName(UPDATED_TIME, new Date(), metaObject);
        }
    }

}
